const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    car_model_list: [],
    num: '',
    selected_car_model_list: [],
    carType: 0,
    alphaList:[],
    toView:'inToViewY'
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.info(options)
    // this.setData({
    //   num: options.num
    // })
    var that=this
    wx.getStorage({
      key: 'carTypeList',
      success(res) {
        console.info(res)
        if(res.errMsg=="getStorage:ok"&&res.data){
          that.initCarModelType(res.data, options)
        }else{
          wx.request({
            url: app.getHost() + "/datalake/v1/brandMakes/all",
            method: "GET",
            header: {
              'content-type': 'application/json' // 默认值
            },
            success: res => {
              if (res.statusCode == 200) {
                that.initCarModelType(res.data, options)
                wx.setStorage({
                  key: "carTypeList",
                  data: res.data,
                  success: function (res) {
                    console.info(res)
                  }
                })
              }
            },
            complete: function (res) { }
          });
        }
      },fail(res){
        console.info(res)
        wx.request({
          url: app.getHost() + "/datalake/v1/brandMakes/all",
          method: "GET",
          header: {
            'content-type': 'application/json' // 默认值
          },
          success: res => {
            if (res.statusCode == 200) {
              that.initCarModelType(res.data, options)
              wx.setStorage({
                key: "carTypeList",
                data: res.data,
                success: function (res) {
                  console.info(res)
                }
              }) 

            }
          },
          complete: function (res) { }
        });
      }
    })
    

  },

  initCarModelType: function (data, options){
    let car_model_list = data;
    let selected_car_model_list = [];
    let { selectedCarModelType, carType } = options;
    handleCarModelListToggle(car_model_list, 'contract', 'all');

    let alphaList = [];
    for (var i in car_model_list) {
      if (car_model_list[i].alpha != "车型类别") {
        alphaList.push(car_model_list[i].alpha)
      }

    }
    if (selectedCarModelType.trim() != '+') {

      selectedCarModelType.split(',').forEach(function (item) {
        let result, brand;
        let items = item.split('-');

        if (items.length == 2) {
          brand = items[0]
          item = items[1];
        }

        result = handleCarModelListAndSelectedCarModelList(car_model_list, selected_car_model_list, 'mark', item, carType);

        car_model_list = result.car_model_list
        selected_car_model_list = result.selected_car_model_list;
        handleCarModelListToggle(car_model_list, 'expand', brand);
      })
    }

    this.setData({
      car_model_list,
      selected_car_model_list,
      carType,
      alphaList: alphaList
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  bindtapMaker: function(e) {

    let { selected_car_model_list, carType } = this.data;
    selected_car_model_list = removeCarModelList(selected_car_model_list, '+');
    // selected_car_model_list.push('+');

    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1];   //当前页面
    var prevPage = pages[pages.length - 2];  //上一个页面
    prevPage.setData({
      car_model: selected_car_model_list.join(','),
      carType: carType
    })
    wx.navigateBack({
      delta: 1
    })

  },
  btn_cancle: function (e) {
    wx.navigateBack({
      delta: 1
    })
  },
  scrollToViewFn:function(e){
    let _id=e.target.dataset.id;
    this.setData({
      toView: 'inToView' + _id
    })
  },
  handleSelectedCarModelType: function (e) {

    let { maker, isSelected, carType } = e.currentTarget.dataset;

    this.handleSelected(isSelected ? 'unmark' : 'mark', maker, carType);
  },
  handleSelected: function (markType, markName, carType) {

    let { car_model_list, selected_car_model_list } = this.data;
    let result;

    result = handleCarModelListAndSelectedCarModelList(car_model_list, selected_car_model_list, markType, markName, carType);

    this.setData({
      car_model_list: result.car_model_list,
      selected_car_model_list: result.selected_car_model_list,
      carType
    });
  },
  handleToggleBrand: function(e) {
    let { toggleState, brandName } = e.currentTarget.dataset;
    let { car_model_list } = this.data;
    // let toggelState = '';
    if (toggleState == 'contract') {
      toggleState = 'expand';
    } else {
      toggleState = 'contract';
    }

    let result = handleCarModelListToggle(car_model_list, toggleState, brandName);

    this.setData({
      car_model_list: result
    });
  }

})


function handleCarModelListAndSelectedCarModelList(car_model_list, selected_car_model_list, markType, markName, carType) {
  car_model_list.forEach(function (alpha) {
    alpha.list.forEach(function (brand) {
      if (carType == 1) {
        if (brand.brand == markName) {

          if (markType == 'mark') {
            brand.isSelected = true;
            selected_car_model_list.push(markName);
          } else if (markType == 'unmark') {
            brand.isSelected = false;
            selected_car_model_list = removeCarModelList(selected_car_model_list, markName);
          }
        }
      } else {

        brand.isSelected = false;
        selected_car_model_list = removeCarModelList(selected_car_model_list, brand.brand);
      }
      brand.list.forEach(function (item) {

        if (carType == 2) {
          if (item.maker == markName) {
            if (markType == 'mark') {
              item.isSelected = true;
              
              selected_car_model_list.push(brand.brand + '-' + markName);
            } else if (markType == 'unmark') {
              item.isSelected = false;
              selected_car_model_list = removeCarModelList(selected_car_model_list, markName);
            }
          }
        } else {
          item.isSelected = false;
          selected_car_model_list = removeCarModelList(selected_car_model_list, item.maker);
        }
      });
    });
  });

  return {
    car_model_list,
    selected_car_model_list
  }
}

function removeCarModelList(selected_car_model_list, markName) {
  let indexAt = -1;
  selected_car_model_list.map(function (item, index) {
    let items = item.split('-');

    if (items.length == 2) {
      item = items[1];
    }

    if (item == markName) {
      indexAt = index;
    }
  })
  
  if (indexAt >= 0) {
    selected_car_model_list.splice(indexAt, 1);
  }
  return selected_car_model_list;
}

function handleCarModelListToggle(car_model_list, toggleState, brandName) {
  
  car_model_list.forEach(function (alpha) {
    alpha.list.forEach(function (brand) {
      if (brand.brand == brandName || 'all' == brandName) {
        brand.toggleState = toggleState;
      }
    });
  });

  return car_model_list;
}